import { defineStore } from 'pinia';
import { http } from '@/utils/request';
import { ref } from 'vue';
import type { CartItem, CartItemList } from '@/types';
import { message } from '@/components/XtxUI';
import useStore from '..';
export const useCartStore = defineStore('cart', {
  persist: true,
  state() {
    return {
      cartInfo: [] as CartItemList,
    };
  },
  getters: {
    // 有效商品参数：库存大于0的商品
    effectiveCartCount(state) {
      let count = 0;
      state.cartInfo.forEach((item) => {
        if (item.stock > 0) {
          count += item.count;
        }
      });
      return count;
    },
    effectiveCartList(state) {
      return state.cartInfo.filter((item) => item.stock > 0);
    },
    effectiveMoney(state) {
      let moeny = 0;
      this.effectiveCartList.forEach((item) => {
        if (item.selected) {
          moeny += item.count * parseFloat(item.price);
        }
      });
      return moeny.toFixed(2); //固定为小数点后两位
    },
    // 选中的商品数量
    selectCount() {
      let count = 0;
      this.effectiveCartList.forEach((item) => {
        if (item.selected) {
          count += item.count;
        }
      });
      return count;
    },
    // 是否全部选中
    selectedAll() {
      // 使用this就是没有类型提示。
      const result =
        this.effectiveCartList.length > 0 &&
        this.effectiveCartList.every((item) => item.selected == true);

      console.log('selectedall', result);

      return result;
    },

    // 是否登录
    isMemberLogin(): boolean {
      const member = useStore().member;
      return member.isLogin;
    },
  },
  actions: {
    // 添加购物车
    async addCart(data: CartItem) {
      try {
        const { skuId, count } = data;
        if (this.isMemberLogin) {
          const res = await http('post', '/member/cart', { skuId, count });
          console.log('购物车', res);
          this.getCartInfo();
        } else {
          // 未登录下的购物车
          const cartItem = this.cartInfo.find((item) => item.skuId == skuId);
          console.log(cartItem, 'cartItem');

          if (cartItem) {
            // 如果购物车里已经有了则直接加数量即可
            cartItem.count += count;
          } else {
            this.cartInfo.unshift(data);
          }
        }
        message({
          type: 'success',
          text: '加入购物车成功！',
        });
      } catch (e) {
        message({
          type: 'error',
          text: '加入购物车失败',
        });
      }
    },

    // 获取购物车
    async getCartInfo() {
      try {
        if (this.isMemberLogin) {
          const res = await http<CartItemList>('get', '/member/cart');
          console.log(res, '购物车信息');
          this.cartInfo = res.data.result;
        } else {
          // 要获取最新的商品信息，防止库存更新和价格更新。
          this.cartInfo.forEach(async (item) => {
            const res = await http<CartItem>(
              'get',
              '/goods/stock/' + item.skuId
            );
            // console.log(res, '获取最新信息');
            item.stock = res.data.result.stock;
            item.isEffective = res.data.result.isEffective;
            item.nowPrice = res.data.result.price;
          });
        }
      } catch (e) {
        message({
          type: 'error',
          text: '获取购物车信息失败',
        });
      }
    },

    // 删除购物车
    async deleteCart(skuId: string) {
      try {
        if (this.isMemberLogin) {
          const res = await http('delete', '/member/cart', { ids: [skuId] });
          console.log('购物车删除', res);
          this.getCartInfo();
        } else {
          this.cartInfo = this.cartInfo.filter((item) => item.skuId != skuId);
        }

        message({
          type: 'success',
          text: '删除成功！',
        });
      } catch (e) {
        console.log('删除失败！');
      }
    },

    // 修改商品，设置选中和数量
    async updateCart(
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      if (this.isMemberLogin) {
        const res = await http('put', '/member/cart/' + skuId, data);
        console.log('修改', res);
        this.getCartInfo();
      } else {
        const cartItem = this.cartInfo.find((item) => item.skuId == skuId);
        if (cartItem) {
          if (data.selected == false || data.selected == true) {
            cartItem.selected = data.selected;
          }
          if (data.count) {
            cartItem.count = data.count;
          }
        }
      }
    },

    // 设置全选/全不选
    async selectAllorNot(selected: boolean) {
      if (this.isMemberLogin) {
        const res = await http('put', '/member/cart/selected', { selected });
        // console.log(res, '设置全选、全不选');
        // 重新获取数据
        this.getCartInfo();
      } else {
        this.cartInfo.map((item) => (item.selected = selected));
      }
    },

    // 清空购物车的数据
    clearCart() {
      this.cartInfo = [];
    },

    // 合并购物车
    async mergeCart() {
      // 映射需要的参数
      const data = this.cartInfo.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count,
      }));
      console.log(data, '映射的参数');
      await http('post', '/member/cart/merge', data);
      this.getCartInfo();
    },
  },
});
